<template>
  <div class="image-uploader">
    <el-upload
      :action="uploadUrl"
      list-type="picture-card"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <div v-if="imageUrl" class="cropper-container">
      <vue-cropper
        ref="cropper"
        :img="imageUrl"
        :output-size="{ quality: 1 }"
        :output-type="'jpeg'"
        info="true"
        :can-scale="false"
        :auto-crop="true"
        :auto-crop-area="1"
        :fixed="true"
        :fixed-number="[1, 1]"
        :fixed-box="true"
        @real-time="realTime"
      />
      <div class="cropper-footer">
        <el-button type="primary" @click="cropImage">裁剪</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import VueCropper from 'vue-cropper'

export default {
  components: {
    'vue-cropper': VueCropper
  },
  data() {
    return {
      fileList: [],
      imageUrl: '',
      uploadUrl: '/content/attachment/upload'
    }
  },
  methods: {
    beforeUpload(file) {
      // 可以在这里添加文件类型或大小的校验
      return true;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleSuccess(response, file, fileList) {
      // 处理上传成功的逻辑
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    realTime(data) {
      // 实时预览裁剪效果
    },
    cropImage() {
      this.$refs.cropper.getCropData((data) => {
        // 这里可以调用上传接口，将裁剪后的图片上传到服务器
        console.log(data);
      });
    }
  }
}
</script>

<style scoped>
.image-uploader {
  margin: 20px;
}
.cropper-container {
  margin-top: 20px;
}
.cropper-footer {
  text-align: center;
  margin-top: 10px;
}
</style>
